import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios'
import { message } from 'ant-design-vue'
import { getToken, removeToken } from './storage'
import router from '@/router'

// 请求重试配置
interface RetryConfig {
  count: number
  delay: number
}

interface CustomAxiosRequestConfig extends AxiosRequestConfig {
  retryConfig?: RetryConfig
  retryCount?: number
}

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '/api-admin',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在请求头中添加token
    const token = getToken()
    if (token) {
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    if (data.code && data.code !== 200) {
      message.error(data.message || '请求失败')
      // 处理401错误，清除用户信息并跳转到登录页
      if (data.code === 401) {
        removeToken()
        router.push('/login')
      }
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    return data
  },
  (error: AxiosError) => {
    // 自动重试机制
    const config = error.config as CustomAxiosRequestConfig
    if (config?.retryConfig && (!config.retryCount || config.retryCount < config.retryConfig.count)) {
      config.retryCount = config.retryCount || 0
      config.retryCount += 1
      
      // 延迟重试
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(service(config))
        }, config.retryConfig!.delay)
      })
    }
    
    // 处理错误信息
    let errorMessage = '网络异常，请稍后再试'
    if (error.response) {
      const status = error.response.status
      switch (status) {
        case 401:
          errorMessage = '登录已过期，请重新登录'
          // 清除token并跳转到登录页
          removeToken()
          router.push('/login')
          break
        case 403:
          errorMessage = '无权访问'
          break
        case 404:
          errorMessage = '请求的资源不存在'
          break
        case 500:
          errorMessage = '服务器错误，请联系管理员'
          break
        default:
          errorMessage = `请求错误(${status})`
      }
    } else if (error.message && error.message.includes('timeout')) {
      errorMessage = '请求超时，请刷新重试'
    }
    
    message.error(errorMessage)
    return Promise.reject(error)
  },
)

// 导出封装的请求方法
const request = {
  get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, { params, ...config })
  },
  
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config)
  },
  
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config)
  },
  
  delete<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, { params, ...config })
  },
  
  upload<T = any>(url: string, file: File, filename = 'file', config?: AxiosRequestConfig): Promise<T> {
    const formData = new FormData()
    formData.append(filename, file)
    
    return service.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      ...config,
    })
  },
  
  // 文件下载方法
  download(url: string, params?: any, filename?: string): void {
    service({
      url,
      method: 'GET',
      params,
      responseType: 'blob',
    }).then((response) => {
      // 获取文件名
      let fname = filename
      if (!fname) {
        const contentDisposition = response.headers['content-disposition']
        if (contentDisposition) {
          const match = contentDisposition.match(/filename=(.+)/)
          if (match) {
            fname = match[1]
          }
        }
        fname = fname || 'download'
      }
      
      // 创建Blob链接并下载
      const blob = new Blob([response.data])
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = fname
      link.click()
      URL.revokeObjectURL(link.href)
    }).catch((error) => {
      message.error('下载失败')
      console.error('下载失败', error)
    })
  },
  
  // 配置重试
  retry<T = any>(config: CustomAxiosRequestConfig, retryConfig: RetryConfig): Promise<T> {
    const configWithRetry = {
      ...config,
      retryConfig,
    }
    return service(configWithRetry as AxiosRequestConfig) as Promise<T>
  },
}

export default request 